using System;
using JustePort;

namespace AirTunesStreamer
{
    class Streamer: IDisposable
    {
        public event Action<Exception> OnError;
        private SoundCapture.DirectSoundCapture _recorder;
        private RAOPClient _service;
        private double _volume = RAOPClient.VOLUME_DEF;

        private void DataArrived(byte[] buf)
        {
            try
            {
                byte[] alac = BitBuffer.EncodeALAC(buf);
                _service.SendSample(alac);
            }
            catch (Exception e)
            {
                if (OnError != null)
                    OnError(e);
            }
        }

        public void SetVolume(double volume)
        {
            _volume = RAOPClient.VOLUME_MIN + (volume * (RAOPClient.VOLUME_MAX - RAOPClient.VOLUME_MIN));
            //Console.WriteLine("{0}, {1}", volume, _volume);
            if (_service != null)
            {
                _service.Volume = _volume;
            }
        }

        public void Stop()
        {
            if (_service != null)
                _service.Disconnect();
            if (_recorder != null)
                _recorder.Stop();
        }

        public void Start(string hostOrIP)
        {
            Stop();

            if (_service == null || _service.Host != hostOrIP)
                _service = new RAOPClient(hostOrIP);
            _service.Volume = _volume;
            _service.Connect();

            if (_recorder == null)
                _recorder = new SoundCapture.DirectSoundCapture(BitBuffer.FrameSize, 44100, 16, 2, DataArrived, true);
            else
                _recorder.Start();
        }

        public void Dispose()
        {
            if (_recorder != null)
            {
                _recorder.Dispose();
                _recorder = null;
            }

            if (_service != null)
            {
                _service.Disconnect();
                _service = null;
            }
        }
    }
}
